var mysql = require('mysql');
var pool  = mysql.createPool({
    host     : '127.0.0.1',
    user     : 'root',
    password : 'jcjh.251314',
    database: 'ipmall'
});

exports.getUsers = function(callback) {
    pool.getConnection(function(err, connection) {
        if(err) { 
            console.error(err); 
            callback(true); 
            return; 
        }
        var sql = "SELECT id,name FROM users";
        connection.query(sql, [], function(err, results) {
            connection.release(); // always put connection back in pool after last query
            if(err) { 
                console.error(err); 
                callback(true); 
                return; 
            }
            callback(false, results);
        });
    });
}

exports.getHook2Entry = function(emailId){

    var sql = `SELECT * FROM \`ipmall\`.\`mailhook2\` WHERE \`emailId\`=\'${emailId}\'`;
    console.log('getHook2Entry emid: ' + emailId);
    var p = new Promise((resolve, reject)=>{

        pool.getConnection((poolErr, con)=>{
            if(poolErr)     {
                reject(poolErr);
                console.error(poolErr);
                return;
            }

            con.query(sql, function (conErr, results, fields) {
                if(conErr){
                    reject(conErr);
                    console.error(conErr);
                }else{
                    resolve(results[0]);
                    console.log('emid found: ' + emailId)
                }
            });
        })
    });

    return p;
};

exports.updHook2Entry = function(event, subStatDesc, emailId){

    var timestamp2 = timestamp2 = new Date().getTime();
    var message = subStatDesc == undefined ? '' :subStatDesc;
    var sql = `UPDATE \`ipmall\`.\`mailhook2\` SET message = '${message}',event='${event}',timestamp2='${timestamp2}' WHERE \`mailhook2\`.emailId = '${emailId}';`;
    console.log(`going to update: ${emailId}`);
    var p = new Promise((resolve, reject)=>{


    pool.query(sql, (conErr, results, fields)=>{
        if(conErr)  {
            console.error(conErr);
            reject(conErr);
        }
        else{
            resolve({error: conErr, results: results});
            console.log('db updated: ' + sql)
        }
    })
})

    return p;
};
